import axios from 'axios'
import { getToken, setLoginStatus, setToken } from './auth'
import router from '../router'
import { Toast } from 'vant'
import { Dialog } from "vant";
import {_local} from "@/utils/storage"

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})

// json 请求
service.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'

// 全局请求
service.interceptors.request.use(
  (config) => {
    if (config.url === 'v1/accessor/register') {
      Toast.loading({
        duration: 0,
        message: '登录中...',
        forbidClick: true
      })
    }
    if (config.url === 'v1/user/certification') {
      Toast.loading({
        duration: 0,
        message: '身份证核验中...',
        forbidClick: true
      })
    }
    const token = getToken()
    _local.set("token",token)
    if (token) {
      config.headers['Authorization'] = 'bearer ' + token
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 全局响应处理
service.interceptors.response.use(
  (response) => {
    Toast.clear()
    const code = response.data.code
    const msg = response.data.message
    // console.log("全局状态：",JSON.stringify(response))
    if (response.status > 299 || response.status < 200) {
      router.push('/loading')
    }
    // 用户区间错误全局 warning
    if (code > 2000 && code <= 3000) {
      // token 过期
      if (code === 2014) {
        router.push('/login')
        setLoginStatus(0)
        Dialog
          .alert({
            title: "温馨提示",
            message: "登录状态已失效，请重新验证登录",
            confirmButtonColor: "#45b7cb",
            theme: "round-button",
            messageAlign:"left"
          })
          .then(() => { });
        return
      }
    }
    // 全局错误异常
    if (code > 3000 && code <= 4000) {
      // token 失效跳转到登录
      if (code === 3023) {
        router.push('/login')
        setLoginStatus(0)
        Dialog
          .alert({
            title: "温馨提示",
            message: "登录状态已失效，请重新验证登录",
            confirmButtonColor: "#45b7cb",
            theme: "round-button",
            messageAlign:"left"
          })
          .then(() => { });
        return
      }
    }
    const token = response.headers['x-token']
    if (token) {
      setToken(token)
      setLoginStatus(1)
    }
    return response.data
  },
  (err) => {
    return Promise.reject(err)
  }
)

export default service
